<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>高级代码安全分析器 | 多语言静态动态分析</title>
    <script src="https://unpkg.com/@tailwindcss/browser@4"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    <style>
        body {
            font-family: 'Inter', sans-serif;
            background-color: #f8fafc;
        }

        .custom-file-button {
            background-color: #dc3545;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            transition: all 0.3s ease;
            font-weight: 500;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .custom-file-button:hover {
            background-color: #c82333;
            transform: translateY(-1px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }

        .modal {
            display: none;
            position: fixed;
            z-index: 50;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            overflow: auto;
            background-color: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(2px);
        }

        .modal-content {
            background-color: #fefefe;
            margin: 5% auto;
            padding: 24px;
            border-radius: 12px;
            width: 90%;
            max-width: 800px;
            box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
            animation: modalFadeIn 0.3s ease-out;
            max-height: 85vh;
            display: flex;
            flex-direction: column;
        }

        @keyframes modalFadeIn {
            from {
                opacity: 0;
                transform: translateY(-20px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .close {
            color: #6b7280;
            float: right;
            font-size: 28px;
            font-weight: bold;
            transition: color 0.2s;
        }

        .close:hover,
        .close:focus {
            color: #4b5563;
            text-decoration: none;
            cursor: pointer;
        }

        .dropzone {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 32px;
            text-align: center;
            margin: 16px 0;
            transition: all 0.3s;
            background-color: #f9fafb;
        }

        .dropzone.active {
            border-color: #4f46e5;
            background-color: #eef2ff;
        }

        .issue {
            padding: 16px;
            margin: 8px 0;
            border-radius: 8px;
            transition: all 0.3s ease;
            cursor: pointer;
            border-left: 4px solid;
        }

        .issue:hover {
            transform: translateX(2px);
        }

        .issue-warning {
            background-color: #fffbeb;
            color: #92400e;
            border-left-color: #f59e0b;
        }

        .issue-danger {
            background-color: #fef2f2;
            color: #991b1b;
            border-left-color: #ef4444;
        }

        .issue-info {
            background-color: #ecfdf5;
            color: #065f46;
            border-left-color: #10b981;
        }

        .issue-success {
            background-color: #f0fdf4;
            color: #166534;
            border-left-color: #22c55e;
        }

        .history-item {
            padding: 12px 16px;
            margin: 8px 0;
            border-radius: 8px;
            background-color: white;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            transition: all 0.2s ease;
            cursor: pointer;
            border-left: 3px solid #4f46e5;
        }

        .history-item:hover {
            transform: translateX(4px);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }

        .tab {
            padding: 12px 24px;
            cursor: pointer;
            border: none;
            background-color: transparent;
            font-weight: 500;
            color: #6b7280;
            position: relative;
            transition: all 0.3s ease;
        }

        .tab.active {
            color: #4f46e5;
        }

        .tab.active::after {
            content: '';
            position: absolute;
            bottom: 0;
            left: 24px;
            right: 24px;
            height: 3px;
            background-color: #4f46e5;
            border-radius: 3px 3px 0 0;
        }

        .tab-content {
            display: none;
            padding: 24px 0;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .tab-content.active {
            display: block;
        }

        .advice-container {
            margin-top: 12px;
            padding: 12px;
            background-color: #f8fafc;
            border-radius: 6px;
            border-left: 3px solid #4f46e5;
            display: none;
            animation: slideDown 0.3s ease-out;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .advice-title {
            font-weight: 600;
            margin-bottom: 8px;
            color: #4f46e5;
        }

        .advice-content {
            color: #4b5563;
            line-height: 1.6;
        }

        .issue-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 8px;
        }

        .issue-type {
            font-weight: 600;
            margin-right: 10px;
        }

        .issue-line {
            font-size: 0.85em;
            color: #6b7280;
            background-color: rgba(0, 0, 0, 0.05);
            padding: 2px 6px;
            border-radius: 4px;
        }

        .result-scroll {
            max-height: 60vh;
            overflow-y: auto;
            padding-right: 8px;
            margin-bottom: 16px;
        }

        /* 自定义滚动条 */
        .result-scroll::-webkit-scrollbar {
            width: 6px;
        }

        .result-scroll::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 3px;
        }

        .result-scroll::-webkit-scrollbar-thumb {
            background: #c7d2fe;
            border-radius: 3px;
        }

        .result-scroll::-webkit-scrollbar-thumb:hover {
            background: #a5b4fc;
        }

        .language-tag {
            display: inline-block;
            padding: 2px 8px;
            border-radius: 12px;
            font-size: 0.75rem;
            font-weight: 500;
            margin-left: 8px;
            vertical-align: middle;
        }

        .python-tag {
            background-color: #eef2ff;
            color: #4f46e5;
        }

        .java-tag {
            background-color: #f5f3ff;
            color: #7c3aed;
        }

        .c-tag {
            background-color: #ecfdf5;
            color: #059669;
        }

        .cpp-tag {
            background-color: #f0fdf4;
            color: #16a34a;
        }

        .js-tag {
            background-color: #fef9c3;
            color: #ca8a04;
        }

        .docx-tag {
            background-color: #eff6ff;
            color: #2563eb;
        }

        .file-icon {
            margin-right: 8px;
            color: #4f46e5;
        }

        .stats-card {
            background-color: white;
            border-radius: 8px;
            padding: 16px;
            box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
            margin-bottom: 16px;
        }

        .stats-title {
            font-size: 0.875rem;
            color: #6b7280;
            margin-bottom: 8px;
        }

        .stats-value {
            font-size: 1.5rem;
            font-weight: 600;
            color: #111827;
        }

        .stats-danger {
            color: #ef4444;
        }

        .stats-warning {
            color: #f59e0b;
        }

        .stats-success {
            color: #10b981;
        }
    </style>
</head>

<body class="flex flex-col min-h-screen">
    <header class="bg-gradient-to-r from-indigo-600 to-indigo-700 text-white p-6 shadow-lg">
        <div class="container mx-auto">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-3xl font-bold">高级代码安全分析器</h1>
                    <p class="text-indigo-100 mt-2">静态与动态代码安全分析，支持多种编程语言</p>
                </div>
                <div class="hidden md:block">
                    <div class="flex space-x-2">
                        <span class="language-tag python-tag">Python</span>
                        <span class="language-tag java-tag">Java</span>
                        <span class="language-tag c-tag">C</span>
                        <span class="language-tag cpp-tag">C++</span>
                        <span class="language-tag js-tag">JavaScript</span>
                        <span class="language-tag docx-tag">DOCX</span>
                    </div>
                </div>
            </div>
        </div>
    </header>
    <main class="flex-grow p-4 md:p-8">
        <div class="container mx-auto">
            <div class="bg-white rounded-xl shadow-md overflow-hidden">
                <div class="flex border-b border-gray-200">
                    <button id="uploadTab" class="tab active">
                        <i class="fas fa-upload file-icon"></i>上传分析
                    </button>
                    <button id="historyTab" class="tab">
                        <i class="fas fa-history file-icon"></i>分析历史
                    </button>
                    <button id="aboutTab" class="tab">
                        <i class="fas fa-info-circle file-icon"></i>关于
                    </button>
                </div>

                <div id="uploadContent" class="tab-content active p-6">
                    <h2 class="text-2xl font-bold mb-6 text-gray-800">
                        <i class="fas fa-search mr-2 text-indigo-600"></i>上传代码文件进行安全分析
                    </h2>
                    <p class="text-gray-600 mb-6">支持的文件类型：.py、.java、.c、.cpp、.js、.docx</p>
                    
                    <div id="dropzone" class="dropzone">
                        <i class="fas fa-cloud-upload-alt text-5xl text-indigo-400 mb-4"></i>
                        <p class="text-gray-600 mb-2">拖放文件到此处或</p>
                        <input type="file" id="codeFile" class="hidden" accept=".py,.java,.c,.cpp,.js,.docx">
                        <button id="customFileButton" class="custom-file-button mt-2">
                            <i class="fa-solid fa-file-upload mr-2"></i> 选择代码文件
                        </button>
                        <p class="text-sm text-gray-500 mt-4">最大文件大小: 5MB</p>
                    </div>
                    <div id="fileInfo" class="mt-4 flex items-center">
                        <span id="selectedFileName" class="ml-2 text-gray-700 font-medium"></span>
                    </div>
                    
                    <div class="mt-6 flex justify-center">
                        <button id="analyzeButton"
                            class="bg-indigo-600 text-white px-6 py-3 rounded-lg hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-indigo-500 focus:ring-opacity-50 transition-all transform hover:scale-105 shadow-md">
                            <i class="fa-solid fa-magnifying-glass mr-2"></i> 分析代码
                        </button>
                    </div>
                </div>

                <div id="historyContent" class="tab-content p-6">
                    <div class="flex justify-between items-center mb-6">
                        <h2 class="text-2xl font-bold text-gray-800">
                            <i class="fas fa-history mr-2 text-indigo-600"></i>分析历史记录
                        </h2>
                        <button id="clearHistory" class="text-sm text-indigo-600 hover:text-indigo-800">
                            <i class="fas fa-trash-alt mr-1"></i>清空历史
                        </button>
                    </div>
                    <div id="historyList" class="space-y-3"></div>
                </div>

                <div id="aboutContent" class="tab-content p-6">
                    <h2 class="text-2xl font-bold mb-6 text-gray-800">
                        <i class="fas fa-info-circle mr-2 text-indigo-600"></i>关于代码安全分析器
                    </h2>
                    
                    <div class="bg-indigo-50 rounded-lg p-6 mb-6">
                        <h3 class="text-xl font-semibold mb-4 text-indigo-800">系统简介</h3>
                        <p class="text-gray-700 mb-4">
                            高级代码安全分析器是一款专业的静态与动态代码安全检测工具，支持多种编程语言的安全漏洞检测，
                            包括Python、Java、C、C++和JavaScript等。系统能够识别常见的安全漏洞模式，
                            如SQL注入、XSS攻击、缓冲区溢出、硬编码凭证等问题。
                        </p>
                        <p class="text-gray-700">
                            本系统旨在帮助开发者在开发早期发现潜在的安全问题，提高代码质量和安全性。
                        </p>
                    </div>
                    
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                        <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                            <h3 class="text-lg font-semibold mb-3 text-gray-800">
                                <i class="fas fa-shield-alt mr-2 text-indigo-600"></i>支持的安全检测
                            </h3>
                            <ul class="space-y-2">
                                <li class="flex items-start">
                                    <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                                    <span>SQL注入检测</span>
                                </li>
                                <li class="flex items-start">
                                    <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                                    <span>跨站脚本(XSS)检测</span>
                                </li>
                                <li class="flex items-start">
                                    <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                                    <span>缓冲区溢出检测</span>
                                </li>
                                <li class="flex items-start">
                                    <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                                    <span>硬编码凭证检测</span>
                                </li>
                                <li class="flex items-start">
                                    <i class="fas fa-check-circle text-green-500 mt-1 mr-2"></i>
                                    <span>不安全的函数调用检测</span>
                                </li>
                            </ul>
                        </div>
                        
                        <div class="bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                            <h3 class="text-lg font-semibold mb-3 text-gray-800">
                                <i class="fas fa-code mr-2 text-indigo-600"></i>支持的编程语言
                            </h3>
                            <ul class="space-y-2">
                                <li class="flex items-center">
                                    <span class="language-tag python-tag mr-2">Python</span>
                                    <span>Python 3.x</span>
                                </li>
                                <li class="flex items-center">
                                    <span class="language-tag java-tag mr-2">Java</span>
                                    <span>Java 8+</span>
                                </li>
                                <li class="flex items-center">
                                    <span class="language-tag c-tag mr-2">C</span>
                                    <span>ANSI C</span>
                                </li>
                                <li class="flex items-center">
                                    <span class="language-tag cpp-tag mr-2">C++</span>
                                    <span>C++11及以上</span>
                                </li>
                                <li class="flex items-center">
                                    <span class="language-tag js-tag mr-2">JavaScript</span>
                                    <span>ECMAScript 6+</span>
                                </li>
                                <li class="flex items-center">
                                    <span class="language-tag docx-tag mr-2">DOCX</span>
                                    <span>Word文档代码分析</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                    
                    <div class="mt-8 bg-white p-6 rounded-lg shadow-sm border border-gray-100">
                        <h3 class="text-lg font-semibold mb-3 text-gray-800">
                            <i class="fas fa-question-circle mr-2 text-indigo-600"></i>使用帮助
                        </h3>
                        <div class="space-y-4">
                            <div>
                                <h4 class="font-medium text-gray-800 mb-1">如何上传文件？</h4>
                                <p class="text-gray-600 text-sm">
                                    点击"选择代码文件"按钮或直接将文件拖放到上传区域。系统支持.py、.java、.c、.cpp、.js和.docx格式的文件。
                                </p>
                            </div>
                            <div>
                                <h4 class="font-medium text-gray-800 mb-1">如何查看分析结果？</h4>
                                <p class="text-gray-600 text-sm">
                                    上传文件后点击"分析代码"按钮，分析完成后会弹出结果窗口。点击问题可以查看详细修复建议。
                                </p>
                            </div>
                            <div>
                                <h4 class="font-medium text-gray-800 mb-1">如何导出结果？</h4>
                                <p class="text-gray-600 text-sm">
                                    在分析结果窗口中点击"导出结果"按钮，可以将分析报告保存为文本文件。
                                </p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </main>
    <footer class="bg-gray-50 text-gray-600 p-6 text-center border-t border-gray-200">
        <div class="container mx-auto">
            <div class="flex flex-col md:flex-row justify-between items-center">
                <div class="mb-4 md:mb-0">
                    &copy; 2025 高级代码安全分析器 | 支持 Python, Java, C, C++, JavaScript 和 DOCX 文件分析
            </div>
        </div>
    </footer>

    <!-- 分析结果模态框 -->
    <div id="resultModal" class="modal">
        <div class="modal-content">
            <span class="close">&times;</span>
            <h2 class="text-2xl font-bold mb-4 text-gray-800">
                <i class="fas fa-file-alt mr-2 text-indigo-600"></i>分析结果
            </h2>
            <div id="resultStats" class="grid grid-cols-3 gap-4 mb-4">
                <div class="stats-card">
                    <div class="stats-title">严重问题</div>
                    <div class="stats-value stats-danger" id="dangerCount">0</div>
                </div>
                <div class="stats-card">
                    <div class="stats-title">警告问题</div>
                    <div class="stats-value stats-warning" id="warningCount">0</div>
                </div>
                <div class="stats-card">
                    <div class="stats-title">通过检查</div>
                    <div class="stats-value stats-success" id="successCount">0</div>
                </div>
            </div>
            <div class="result-scroll" id="resultDetails"></div>
            <div class="mt-4 flex justify-end space-x-3">
                <button id="exportButton" class="bg-indigo-600 text-white px-4 py-2 rounded-lg hover:bg-indigo-700 transition-colors">
                    <i class="fas fa-download mr-2"></i> 导出结果
                </button>
                <button id="closeModal" class="bg-gray-200 text-gray-700 px-4 py-2 rounded-lg hover:bg-gray-300 transition-colors">
                    关闭
                </button>
            </div>
        </div>
    </div>

    <script>
        // DOM元素
        const analyzeButton = document.getElementById('analyzeButton');
        const codeFile = document.getElementById('codeFile');
        const customFileButton = document.getElementById('customFileButton');
        const selectedFileName = document.getElementById('selectedFileName');
        const dropzone = document.getElementById('dropzone');
        const resultModal = document.getElementById('resultModal');
        const resultDetails = document.getElementById('resultDetails');
        const closeBtn = document.querySelector('.close');
        const exportButton = document.getElementById('exportButton');
        const uploadTab = document.getElementById('uploadTab');
        const historyTab = document.getElementById('historyTab');
        const aboutTab = document.getElementById('aboutTab');
        const uploadContent = document.getElementById('uploadContent');
        const historyContent = document.getElementById('historyContent');
        const aboutContent = document.getElementById('aboutContent');
        const historyList = document.getElementById('historyList');
        const closeModal = document.getElementById('closeModal');
        const clearHistory = document.getElementById('clearHistory');
        const dangerCount = document.getElementById('dangerCount');
        const warningCount = document.getElementById('warningCount');
        const successCount = document.getElementById('successCount');

        // 标签页切换
        function switchTab(tab, content) {
            [uploadTab, historyTab, aboutTab].forEach(t => t.classList.remove('active'));
            [uploadContent, historyContent, aboutContent].forEach(c => c.classList.remove('active'));
            
            tab.classList.add('active');
            content.classList.add('active');
        }

        uploadTab.addEventListener('click', () => switchTab(uploadTab, uploadContent));
        historyTab.addEventListener('click', () => {
            switchTab(historyTab, historyContent);
            loadHistory();
        });
        aboutTab.addEventListener('click', () => switchTab(aboutTab, aboutContent));

        // 文件选择处理
        customFileButton.addEventListener('click', () => codeFile.click());

        codeFile.addEventListener('change', updateSelectedFileName);

        function updateSelectedFileName() {
            const file = codeFile.files[0];
            if (file) {
                selectedFileName.textContent = `已选择: ${file.name}`;
                selectedFileName.innerHTML += getFileTypeBadge(file.name);
            } else {
                selectedFileName.textContent = '';
            }
        }

        function getFileTypeBadge(filename) {
            if (filename.endsWith('.py')) return '<span class="language-tag python-tag ml-2">Python</span>';
            if (filename.endsWith('.java')) return '<span class="language-tag java-tag ml-2">Java</span>';
            if (filename.endsWith('.c')) return '<span class="language-tag c-tag ml-2">C</span>';
            if (filename.endsWith('.cpp')) return '<span class="language-tag cpp-tag ml-2">C++</span>';
            if (filename.endsWith('.js')) return '<span class="language-tag js-tag ml-2">JavaScript</span>';
            if (filename.endsWith('.docx')) return '<span class="language-tag docx-tag ml-2">DOCX</span>';
            return '';
        }

        // 拖放区域处理
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            dropzone.addEventListener(eventName, preventDefaults, false);
        });

        function preventDefaults(e) {
            e.preventDefault();
            e.stopPropagation();
        }

        ['dragenter', 'dragover'].forEach(eventName => {
            dropzone.addEventListener(eventName, highlight, false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            dropzone.addEventListener(eventName, unhighlight, false);
        });

        function highlight() {
            dropzone.classList.add('active');
        }

        function unhighlight() {
            dropzone.classList.remove('active');
        }

        dropzone.addEventListener('drop', handleDrop, false);

        function handleDrop(e) {
            const dt = e.dataTransfer;
            const files = dt.files;
            
            if (files.length > 0) {
                codeFile.files = files;
                updateSelectedFileName();
            }
        }

        // 分析按钮点击事件
        analyzeButton.addEventListener('click', async () => {
            const file = codeFile.files[0];
            if (!file) {
                showToast('请选择一个代码文件', 'warning');
                return;
            }

            // 检查文件大小 (5MB限制)
            if (file.size > 5 * 1024 * 1024) {
                showToast('文件大小超过5MB限制', 'error');
                return;
            }

            analyzeButton.disabled = true;
            analyzeButton.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>分析中...';

            const formData = new FormData();
            formData.append('code', file);
            formData.append('filename', file.name);

            try {
                const response = await fetch('/analyze', {
                    method: 'POST',
                    body: formData
                });
                
                if (!response.ok) {
                    throw new Error(`HTTP错误! 状态码: ${response.status}`);
                }
                
                const result = await response.json();
                showResults(file.name, result);
                
                // 如果有历史标签页，刷新历史记录
                if (historyTab.classList.contains('active')) {
                    loadHistory();
                }
            } catch (error) {
                showError(error.message);
            } finally {
                analyzeButton.disabled = false;
                analyzeButton.innerHTML = '<i class="fa-solid fa-magnifying-glass mr-2"></i> 分析代码';
            }
        });

        // 显示分析结果
        function showResults(filename, issues) {
            resultDetails.innerHTML = '';
            
            // 更新统计信息
            const dangerIssues = issues.filter(i => i.severity === 'danger').length;
            const warningIssues = issues.filter(i => i.severity === 'warning').length;
            const successIssues = issues.length === 0 ? 1 : 0;
            
            dangerCount.textContent = dangerIssues;
            warningCount.textContent = warningIssues;
            successCount.textContent = successIssues;
            
            const h3 = document.createElement('h3');
            h3.className = 'text-lg font-bold mb-4 text-gray-800';
            h3.innerHTML = `<i class="fas fa-file-code mr-2 text-indigo-600"></i>${filename} ${getFileTypeBadge(filename)}`;
            resultDetails.appendChild(h3);
            
            if (issues.length > 0) {
                const summary = document.createElement('p');
                summary.className = 'text-gray-600 mb-4';
                summary.textContent = `共发现 ${issues.length} 个安全问题`;
                resultDetails.appendChild(summary);
                
                issues.forEach((issue, index) => {
                    const issueContainer = document.createElement('div');
                    
                    const issueDiv = document.createElement('div');
                    issueDiv.className = 'issue';
                    
                    if (issue.severity === 'danger') {
                        issueDiv.classList.add('issue-danger');
                    } else if (issue.severity === 'warning') {
                        issueDiv.classList.add('issue-warning');
                    } else {
                        issueDiv.classList.add('issue-info');
                    }
                    
                    const headerDiv = document.createElement('div');
                    headerDiv.className = 'issue-header';
                    
                    const typeDiv = document.createElement('span');
                    typeDiv.className = 'issue-type';
                    typeDiv.textContent = `${index + 1}. ${issue.type || '问题'}`;
                    
                    const lineDiv = document.createElement('span');
                    lineDiv.className = 'issue-line';
                    lineDiv.textContent = issue.line ? `第 ${issue.line} 行` : '';
                    
                    headerDiv.appendChild(typeDiv);
                    headerDiv.appendChild(lineDiv);
                    
                    const descDiv = document.createElement('div');
                    descDiv.className = 'text-gray-700';
                    descDiv.textContent = issue.description;
                    
                    issueDiv.appendChild(headerDiv);
                    issueDiv.appendChild(descDiv);
                    
                    const adviceDiv = document.createElement('div');
                    adviceDiv.className = 'advice-container';
                    
                    const adviceTitle = document.createElement('div');
                    adviceTitle.className = 'advice-title';
                    adviceTitle.textContent = '修复建议:';
                    
                    const adviceContent = document.createElement('div');
                    adviceContent.className = 'advice-content';
                    adviceContent.textContent = issue.advice || '暂无具体建议';
                    
                    adviceDiv.appendChild(adviceTitle);
                    adviceDiv.appendChild(adviceContent);
                    
                    issueDiv.addEventListener('click', () => {
                        if (adviceDiv.style.display === 'block') {
                            adviceDiv.style.display = 'none';
                            issueDiv.style.marginBottom = '0';
                        } else {
                            adviceDiv.style.display = 'block';
                            issueDiv.style.marginBottom = '8px';
                        }
                    });
                    
                    issueContainer.appendChild(issueDiv);
                    issueContainer.appendChild(adviceDiv);
                    resultDetails.appendChild(issueContainer);
                });
            } else {
                const p = document.createElement('div');
                p.className = 'issue issue-success';
                p.innerHTML = '<i class="fas fa-check-circle mr-2"></i>未发现安全问题，代码安全检查通过！';
                resultDetails.appendChild(p);
            }
            
            resultModal.style.display = "block";
            document.body.style.overflow = "hidden";
        }

        // 显示错误
        function showError(message) {
            resultDetails.innerHTML = '';
            
            const div = document.createElement('div');
            div.className = 'issue issue-danger';
            div.innerHTML = `<i class="fas fa-exclamation-circle mr-2"></i>发生错误: ${message}`;
            resultDetails.appendChild(div);
            
            resultModal.style.display = "block";
            document.body.style.overflow = "hidden";
        }

        // 关闭模态框
        function closeModalFunc() {
            resultModal.style.display = "none";
            document.body.style.overflow = "auto";
        }

        closeBtn.addEventListener('click', closeModalFunc);
        closeModal.addEventListener('click', closeModalFunc);

        window.addEventListener('click', (event) => {
            if (event.target === resultModal) {
                closeModalFunc();
            }
        });

        // 导出结果
        exportButton.addEventListener('click', () => {
            let content = `安全分析报告\n====================\n\n`;
            
            const title = document.querySelector('#resultDetails h3').textContent;
            content += `文件: ${title.replace(/[^\w\s]/gi, '')}\n\n`;
            
            // 添加统计信息
            content += `安全统计:\n`;
            content += `严重问题: ${dangerCount.textContent}\n`;
            content += `警告问题: ${warningCount.textContent}\n`;
            content += `通过检查: ${successCount.textContent}\n\n`;
            
            const issues = document.querySelectorAll('#resultDetails .issue');
            if (issues.length > 0) {
                content += `发现的问题:\n====================\n\n`;
                
                issues.forEach((issue, index) => {
                    content += `问题 ${index + 1}:\n`;
                    content += `类型: ${issue.querySelector('.issue-type').textContent.replace(/^\d+\.\s/, '')}\n`;
                    
                    const lineText = issue.querySelector('.issue-line').textContent;
                    if (lineText) content += `位置: ${lineText}\n`;
                    
                    content += `描述: ${issue.querySelector('div:not(.issue-header)').textContent}\n`;
                    
                    const advice = issue.nextElementSibling;
                    if (advice && advice.classList.contains('advice-container')) {
                        content += `建议: ${advice.textContent}\n`;
                    }
                    
                    content += '\n';
                });
            } else {
                content += '未发现安全问题，代码检查通过。\n';
            }
            
            const blob = new Blob([content], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            
            const a = document.createElement('a');
            a.href = url;
            a.download = `安全分析报告_${new Date().toISOString().split('T')[0]}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
            
            showToast('导出成功', 'success');
        });

        // 加载历史记录
        async function loadHistory() {
            historyList.innerHTML = '<div class="text-center py-8"><i class="fas fa-spinner fa-spin text-indigo-600 text-2xl"></i></div>';
            
            try {
                const response = await fetch('/history');
                if (!response.ok) {
                    throw new Error('获取历史记录失败');
                }
                
                const history = await response.json();
                renderHistory(history);
            } catch (error) {
                historyList.innerHTML = `<div class="text-red-500 text-center py-4"><i class="fas fa-exclamation-triangle mr-2"></i>加载历史记录失败: ${error.message}</div>`;
            }
        }

        // 渲染历史记录
        function renderHistory(history) {
            historyList.innerHTML = '';
            
            if (history.length === 0) {
                historyList.innerHTML = '<div class="text-center py-8 text-gray-500"><i class="fas fa-history mr-2"></i>暂无历史记录</div>';
                return;
            }
            
            history.forEach(item => {
                const div = document.createElement('div');
                div.className = 'history-item';
                
                const time = new Date(item.timestamp).toLocaleString();
                const title = document.createElement('div');
                title.className = 'font-bold flex items-center';
                title.innerHTML = `<i class="fas fa-file-alt mr-2 text-indigo-600"></i>${item.filename} ${getFileTypeBadge(item.filename)}`;
                
                const meta = document.createElement('div');
                meta.className = 'flex justify-between items-center mt-2';
                
                const timeDiv = document.createElement('div');
                timeDiv.className = 'text-xs text-gray-500';
                timeDiv.textContent = time;
                
                const countDiv = document.createElement('div');
                countDiv.className = 'text-sm font-medium';
                
                if (item.issue_count > 0) {
                    countDiv.innerHTML = `<span class="text-red-500">${item.issue_count} 个问题</span>`;
                } else {
                    countDiv.innerHTML = '<span class="text-green-500">安全</span>';
                }
                
                meta.appendChild(timeDiv);
                meta.appendChild(countDiv);
                
                div.appendChild(title);
                div.appendChild(meta);
                
                div.addEventListener('click', () => {
                    showResults(item.filename, item.issues);
                });
                
                historyList.appendChild(div);
            });
        }

        // 清空历史记录
        clearHistory.addEventListener('click', async () => {
        if (confirm('确定要清空所有分析历史记录吗？此操作不可撤销。')) {
        try {
            const response = await fetch('/clear-history', {
                method: 'POST'
            });
            
            if (!response.ok) {
                throw new Error('清空历史记录失败');
            }
            
            const result = await response.json();
            showToast(result.message || '历史记录已清空', 'success');
            loadHistory(); // 重新加载历史记录(此时应该是空的)
        } catch (error) {
            showToast(error.message, 'error');
        }
    }
});

        // 显示Toast通知
        function showToast(message, type = 'info') {
            const toast = document.createElement('div');
            toast.className = `fixed bottom-4 right-4 px-4 py-2 rounded-lg shadow-lg text-white ${
                type === 'error' ? 'bg-red-500' : 
                type === 'success' ? 'bg-green-500' : 
                type === 'warning' ? 'bg-yellow-500' : 'bg-indigo-500'
            }`;
            toast.textContent = message;
            document.body.appendChild(toast);
            
            setTimeout(() => {
                toast.classList.add('opacity-0', 'transition-opacity', 'duration-300');
                setTimeout(() => toast.remove(), 300);
            }, 3000);
        }

        // 初始化加载历史记录
        loadHistory();
    </script>
</body>

</html>